/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.user;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.Group;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.service.core.GroupManager;
import com.blandware.atleap.service.core.RoleManager;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.webapp.acegi.UserManagerDaoImpl;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.SelectRolesAndGroupsForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.*;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Assigns Roles and Groups to User
 * </p>
 * <p><a href="AssignUserRolesAndGroupsAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.5 $ $Date: 2006/08/03 10:08:01 $
 * @struts.action path="/core/user/assignRolesAndGroups"
 * name="selectRolesAndGroupsForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-user-assignRolesAndGroups"
 * @struts.action-forward name="inputForward"
 * path=".core.user.assignRolesAndGroups"
 * @struts.action-forward name="viewUser"
 * path="/core/user/view.do"
 * redirect="true"
 * @struts.action-forward name="listUsers"
 * path="/core/user/list.do"
 * redirect="true"
 * @struts.action-forward name="callAssignRolesAndGroups"
 * path="/core/user/callAssignRolesAndGroups.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/user/list.do"
 */
public final class AssignUserRolesAndGroupsAction extends BaseAction {
    /**
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The HTTP request we are proceeding
     * @param response The HTTP response we are creating
     * @return an ActionForward instance describing where and how
     *         control should be forwarded, or null if response
     *         has already been completed
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) throws Exception {

        if ( !isCancelled(request) ) {

            String userName = (String) request.getSession().getAttribute(WebappConstants.USER_NAME_KEY);
            if ( GenericValidator.isBlankOrNull(userName) ) {
                if ( log.isWarnEnabled() ) {
                    log.warn("Missing user name. Returning to list...");
                }
                return mapping.findForward("listUsers");
            }

            // acquire POJOs for all selected roles
            RoleManager roleManager = (RoleManager) getBean(Constants.ROLE_MANAGER_BEAN);
            SelectRolesAndGroupsForm selectRolesAndGroupsForm = (SelectRolesAndGroupsForm) form;
            String[] selectedRoleNames = selectRolesAndGroupsForm.getSelectedRoles();

            List roles = new ArrayList();
            for ( int i = 0; i < selectedRoleNames.length; i++ ) {
                String roleName = selectedRoleNames[i];
                Role role = roleManager.retrieveRole(roleName);
                if ( role != null ) {
                    roles.add(role);
                }
            }

            // acquire POJOs for all selected groups
            GroupManager groupManager = (GroupManager) getBean(Constants.GROUP_MANAGER_BEAN);
            String[] selectedGroupNames = selectRolesAndGroupsForm.getSelectedGroups();

            List groups = new ArrayList();
            for ( int i = 0; i < selectedGroupNames.length; i++ ) {
                String groupName = selectedGroupNames[i];
                Group group = groupManager.retrieveGroup(groupName);
                if ( group != null ) {
                    groups.add(group);
                }
            }

            // update user roles and groups
            UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
            User user = userManager.retrieveUser(userName);

            if ( user == null ) {
                // user not found. it might be deleted by someone else
                ActionMessages errors = new ActionMessages();
                errors.add("userNotFound", new ActionMessage("core.user.errors.notFound"));
                saveErrors(request, errors);
                return mapping.findForward("listUsers");
            }

            user.setVersion(Long.valueOf(selectRolesAndGroupsForm.getVersion()));

            // remove roles which were unselected
            // list of roles is copied in order to prevent ConcurrentModificationException to be thrown
            List userRoles = new ArrayList(user.getFreeRoles());
            for ( int i = 0; i < userRoles.size(); i++ ) {
                Role role = (Role) userRoles.get(i);
                if ( !roles.contains(role) ) {
                    user.removeFreeRole(role);
                }
            }
            // add new roles
            for ( Iterator i = roles.iterator(); i.hasNext(); ) {
                Role role = (Role) i.next();
                user.addFreeRole(role);
            }

            // remove groups which were unselected
            // list of groups is copied in order to prevent ConcurrentModificationException to be thrown
            List userGroups = new ArrayList(user.getGroups());
            for ( int i = 0; i < userGroups.size(); i++ ) {
                Group group = (Group) userGroups.get(i);
                if ( !groups.contains(group) ) {
                    group.removeUser(user);
                    List groupRoles = group.getRoles();
                    for (int j = 0; j < groupRoles.size(); j++) {
                        Role role = (Role) groupRoles.get(j);
                        user.removeRole(role, group);
                    }
                }
            }
            // add new groups
            for ( Iterator i = groups.iterator(); i.hasNext(); ) {
                Group group = (Group) i.next();
                group.addUser(user);
                List groupRoles = group.getRoles();
                for (int j = 0; j < groupRoles.size(); j++) {
                    Role role = (Role) groupRoles.get(j);
                    user.addRole(role, group);
                }
            }

            try {
                userManager.updateUser(user);

                if (user.getName().equals(request.getRemoteUser())) {
                    UserManagerDaoImpl userManagerDaoImpl = (UserManagerDaoImpl) getBean(Constants.USER_DETAILS_SERVICE_BEAN);
                    userManagerDaoImpl.updateUser(user);
                }
            } catch ( ObjectOptimisticLockingFailureException e ) {
                // user was updated or deleted by another transaction
                ActionMessages errors = new ActionMessages();
                errors.add("updateFailed", new ActionMessage("core.user.errors.updateFailed"));
                saveErrors(request, errors);
                request.setAttribute(WebappConstants.USER_NAME_KEY, userName);
                return mapping.findForward("callAssignRolesAndGroups");
            }

            // flush CP cache to avoid a situation when user permissions for
            // CP menu items are changed but he/she still obtains cached version
            // of page
            CacheUtil cacheUtil = CacheUtil.getInstance(request);
            cacheUtil.flushContentPageCache();
        }
        return mapping.findForward("listUsers");
    }
}